# _*_ coding: utf-8 _*_
"""
Time:     2024/8/22
Author:   2051261
File:     scheduler.py
"""
import asyncio
import signal

from apscheduler.schedulers.asyncio import AsyncIOScheduler

from mine.project.log import log_manager as logger
from mine.scheduler.manager import Manager
from mine.scheduler.shutdown import run_background

import signal
import asyncio
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.cron import CronTrigger
import logging


class SchedulerManager:

    def __init__(self, apscheduler_config: dict = None):
        self.scheduler = AsyncIOScheduler()
        if apscheduler_config:
            self.scheduler.configure(apscheduler_config)
        self.loop = asyncio.get_event_loop()

    def _register_signals(self):
        # 为信号处理程序注册 SIGINT 和 SIGTERM 信号
        for sig in (signal.SIGINT, signal.SIGTERM):
            try:
                self.loop.add_signal_handler(sig, self._handle_shutdown_signal)
            except NotImplementedError:
                logger.warning(f"Signal handling is not supported on this platform.")

    def _handle_shutdown_signal(self):
        """处理信号，优雅关闭调度器"""
        logger.info("Received shutdown signal, stopping scheduler...")
        self.loop.create_task(self.stop())

    async def stop(self):
        """停止调度器并退出事件循环"""
        if self.scheduler.running:
            logger.info(f"Stopping scheduler...")
            self.scheduler.shutdown(wait=True)  # 等待任务完成再停止
            logger.info("Scheduler stopped.")
        else:
            logger.info("Scheduler was already stopped or not running.")

        # 停止事件循环退出
        self.loop.stop()

    def start(self):
        """启动调度器"""
        self.scheduler.start()
        logger.info("Scheduler starting.")

    async def register_job(self, func, trigger, job_id, **trigger_param):
        """
        注册任务到调度器
        * trigger_param 示例：
            CronTrigger.FIELD_NAMES
            ('year', 'month', 'day', 'week', 'day_of_week', 'hour', 'minute', 'second')
        """
        try:
            self.scheduler.add_job(func, trigger=trigger, id=job_id, **trigger_param)
            func_name = getattr(func, '__name__', str(func))
            logger.info(f"[func:{func_name}] [job ID:{job_id}] Job registered successfully.")
        except Exception as e:
            logger.error(f"Failed to register job [job ID:{job_id}] due to error: {e}")

    def get_registered_jobs(self):
        """获取所有注册的作业信息"""
        jobs = self.scheduler.get_jobs()
        job_list = [{"Job ID": job.id, "Trigger": str(job.trigger),
                     "Next Run Time": job.next_run_time.strftime('%Y-%m-%d %H:%M:%S') if job.next_run_time else 'N/A'}
                    for job in jobs]
        return job_list


scheduler_manager = SchedulerManager()


def run():
    return run_background(scheduler_manager.obj, interval=3)
